<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单记录 - OKX 数据展示</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-datepicker@1.9.0/dist/css/bootstrap-datepicker.min.css">
    <style>
        body {
            background-color: #f4f7fa;
            font-family: Arial, sans-serif;
        }
        .navbar {
            background-color: #0c2461;
        }
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #0c2461;
            color: white;
            border-radius: 10px 10px 0 0;
            padding: 15px;
            font-weight: bold;
        }
        .order-row:hover {
            background-color: #f5f5f5;
        }
        .order-row .text-success {
            color: #2ed573 !important;
            font-weight: bold;
        }
        .order-row .text-danger {
            color: #ff4757 !important;
            font-weight: bold;
        }
        .loading {
            display: flex;
            justify-content: center;
            padding: 20px;
        }
        .filter-form {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <!-- 引入导航栏片段 -->
    <div th:replace="fragments/navbar :: navbar"></div>

    <div class="container">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>订单记录</span>
            </div>
            <div class="card-body">
                <!-- 筛选表单 -->
                <div class="filter-form">
                    <h5 class="mb-3">订单查询</h5>
                    <form id="filterForm" class="row g-3">
                        <div class="col-md-3">
                            <label for="instId" class="form-label">产品ID</label>
                            <select id="instId" name="instId" class="form-select">
                                <option value="">-- 全部产品 --</option>
                                <option th:each="account : ${accounts}"
                                        th:value="${account.instId}"
                                        th:text="${account.accountName + ' (' + account.instId + ')'}">
                                </option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="startDate" class="form-label">开始日期</label>
                            <input type="text" class="form-control datepicker" id="startDate" name="startDate">
                        </div>
                        <div class="col-md-3">
                            <label for="endDate" class="form-label">结束日期</label>
                            <input type="text" class="form-control datepicker" id="endDate" name="endDate">
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="button" id="searchBtn" class="btn btn-primary me-2">查询</button>
                            <button type="button" id="deleteBtn" class="btn btn-danger">删除</button>
                        </div>
                    </form>
                </div>

                <!-- 订单数据表格 -->
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>产品ID</th>
                                <th>交易模式</th>
                                <th>订单方向</th>
                                <th>持仓方向</th>
                                <th>张数</th>
                                <th>下单金额</th>
                                <th>下单时间</th>
                                <th>状态</th>
                                <th>订单ID</th>
                            </tr>
                        </thead>
                        <tbody id="ordersTableBody">
                            <tr th:each="order : ${orders}" class="order-row">
                                <td th:text="${order.instId}"></td>
                                <td th:text="${order.tdMode == 'cross' ? '全仓' : '逐仓'}"></td>
                                <td th:text="${(order.side+order.posSide) == 'buylong' ? '开多' :
                                (order.side+order.posSide) == 'sellshort' ? '开空':
                                (order.side+order.posSide) == 'selllong' ? '平多':'平空'
                                }"></td>
                                <td th:text="${order.posSide == 'long' ? '多仓' : '空仓'}"></td>
                                <td th:text="${order.sz}"></td>
                                <td th:text="${order.amount != null ? order.amount : '-'}"></td>
                                <td th:text="${#dates.format(order.createTime, 'yyyy-MM-dd HH:mm:ss')}"></td>
                                <td th:class="${order.code == 0 ? 'text-success' : 'text-danger'}"
                                    th:text="${order.code == 0 ? '成功' : '失败: ' + order.msg}"></td>
                                <td th:text="${order.ordId != null ? order.ordId : '-'}"></td>
                            </tr>
                            <tr th:if="${orders.empty}">
                                <td colspan="9" class="text-center">暂无订单记录</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <!-- 加载提示 -->
                <div id="loadingIndicator" class="loading d-none">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>

                <!-- 错误提示 -->
                <div id="errorAlert" class="alert alert-danger mt-3 d-none" role="alert">
                    获取数据失败，请稍后再试...
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="confirmDeleteModal" tabindex="-1" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmDeleteModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除所选时间范围内的订单记录吗？此操作不可恢复。</p>
                    <div id="deleteDetails" class="alert alert-warning">
                        <!-- 删除详情将在这里显示 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" id="confirmDeleteBtn" class="btn btn-danger">确认删除</button>
                </div>
            </div>
        </div>
    </div>

    <footer class="container mt-5">
        <hr>
        <p class="text-center text-muted">&copy; 2023 OKX 数据展示系统</p>
    </footer>

    <script th:src="@{/js/bootstrap.bundle.min.js}"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-datepicker@1.9.0/dist/js/bootstrap-datepicker.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-datepicker@1.9.0/dist/locales/bootstrap-datepicker.zh-CN.min.js"></script>
    <script>
        // 全局变量
        const loadingIndicator = document.getElementById('loadingIndicator');
        const errorAlert = document.getElementById('errorAlert');
        const tableBody = document.getElementById('ordersTableBody');
        const confirmDeleteModal = new bootstrap.Modal(document.getElementById('confirmDeleteModal'));

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化日期选择器
            $('.datepicker').datepicker({
                format: 'yyyy-mm-dd',
                language: 'zh-CN',
                autoclose: true,
                todayHighlight: true
            });

            // 设置默认日期为今天
            const today = new Date();
            const formattedDate = formatDate(today);
            document.getElementById('startDate').value = formattedDate;
            document.getElementById('endDate').value = formattedDate;

            // 添加查询按钮事件
            document.getElementById('searchBtn').addEventListener('click', searchOrders);

            // 添加删除按钮事件
            document.getElementById('deleteBtn').addEventListener('click', showDeleteConfirmation);

            // 添加确认删除按钮事件
            document.getElementById('confirmDeleteBtn').addEventListener('click', deleteOrders);
        });

        // 格式化日期为 YYYY-MM-DD
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }

        // 显示/隐藏加载中提示
        function showLoading(show) {
            if (show) {
                loadingIndicator.classList.remove('d-none');
            } else {
                loadingIndicator.classList.add('d-none');
            }
        }

        // 显示错误提示
        function showError(message) {
            errorAlert.textContent = message || '获取数据失败，请稍后再试...';
            errorAlert.classList.remove('d-none');
        }

        // 隐藏错误提示
        function hideError() {
            errorAlert.classList.add('d-none');
        }

        // 查询订单
        function searchOrders() {
            const instId = document.getElementById('instId').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            // 参数校验
            if (startDate && !endDate) {
                alert('请选择结束日期');
                return;
            }

            if (!startDate && endDate) {
                alert('请选择开始日期');
                return;
            }

            // 如果没有选择日期范围，则使用当天日期
            const today = formatDate(new Date());
            const useStartDate = startDate || today;
            const useEndDate = endDate || today;

            // 显示加载状态
            showLoading(true);
            hideError();

            // 构建查询参数
            let queryParams = [];
            if (instId) {
                queryParams.push(`instId=${encodeURIComponent(instId)}`);
            }

            // 始终添加日期参数
            queryParams.push(`startDate=${encodeURIComponent(useStartDate)}`);
            queryParams.push(`endDate=${encodeURIComponent(useEndDate)}`);

            // 发送请求
            fetch(`/api/v2/orders${queryParams.length > 0 ? '?' + queryParams.join('&') : ''}`)
                .then(response => response.json())
                .then(data => {
                    renderOrdersTable(data);
                    showLoading(false);
                })
                .catch(error => {
                    console.error('获取订单数据失败:', error);
                    showError('获取订单数据失败: ' + error.message);
                    showLoading(false);
                });
        }

        // 渲染订单表格
        function renderOrdersTable(orders) {
            tableBody.innerHTML = '';

            if (!orders || orders.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="9" class="text-center">暂无订单记录</td>';
                tableBody.appendChild(row);
                return;
            }

            orders.forEach(order => {
                const row = document.createElement('tr');
                row.className = 'order-row';

                // 格式化日期
                const createTime = new Date(order.createTime);
                const formattedTime = createTime.toLocaleString();

                // 格式化交易模式
                const tdMode = order.tdMode === 'cross' ? '全仓' : '逐仓';

                // 格式化订单方向
                const side = (order.side+order.posSide) == 'buylong' ? '开多' :(order.side+order.posSide) == 'sellshort' ? '开空':(order.side+order.posSide) == 'selllong' ? '平多':'平空';

                // 格式化持仓方向
                const posSide = order.posSide === 'long' ? '多仓' : '空仓';

                // 格式化状态
                const statusClass = order.code === 0 ? 'text-success' : 'text-danger';
                const statusText = order.code === 0 ? '成功' : '失败: ' + order.msg;

                row.innerHTML = `
                    <td>${order.instId || '-'}</td>
                    <td>${tdMode}</td>
                    <td>${side}</td>
                    <td>${posSide}</td>
                    <td>${order.sz || '-'}</td>
                    <td>${order.amount || '-'}</td>
                    <td>${formattedTime}</td>
                    <td class="${statusClass}">${statusText}</td>
                    <td>${order.ordId || '-'}</td>
                `;

                tableBody.appendChild(row);
            });
        }

        // 显示删除确认对话框
        function showDeleteConfirmation() {
            const instId = document.getElementById('instId').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            // 参数校验
            if (!startDate || !endDate) {
                alert('请选择开始和结束日期');
                return;
            }

            // 设置删除详情
            let detailsText = `将删除${startDate}至${endDate}期间`;
            if (instId) {
                detailsText += `产品${instId}的`;
            } else {
                detailsText += '所有';
            }
            detailsText += '订单记录。';

            document.getElementById('deleteDetails').textContent = detailsText;

            // 显示确认对话框
            confirmDeleteModal.show();
        }

        // 删除订单
        function deleteOrders() {
            const instId = document.getElementById('instId').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            // 参数校验
            if (!startDate || !endDate) {
                alert('请选择开始和结束日期');
                return;
            }

            // 构建查询参数
            let queryParams = [];
            if (instId) {
                queryParams.push(`instId=${encodeURIComponent(instId)}`);
            }
            queryParams.push(`startDate=${encodeURIComponent(startDate)}`);
            queryParams.push(`endDate=${encodeURIComponent(endDate)}`);

            // 显示加载状态
            showLoading(true);
            hideError();

            // 关闭确认对话框
            confirmDeleteModal.hide();

            // 发送删除请求
            fetch(`/api/v2/orders?${queryParams.join('&')}`, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 0) {
                        alert(result.msg);
                        // 重新加载数据
                        searchOrders();
                    } else {
                        showError(result.msg || '删除订单失败');
                    }
                    showLoading(false);
                })
                .catch(error => {
                    console.error('删除订单失败:', error);
                    showError('删除订单失败: ' + error.message);
                    showLoading(false);
                });
        }
    </script>
</body>
</html>
